package com.scribbles.common.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

@Repository
public abstract class AbstractDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {
	private Class<T> persistentClass;
	private Logger logger = Logger.getLogger(AbstractDAO.class);

	@PersistenceContext(name = "scribblesPU")
	protected EntityManager em;

	protected AbstractDAO(Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

	public void remove(T entity) {
		logger.info("Entity passed : " + entity.toString());
		em.remove(entity);
		logger.info("Entity deleted");
	}
	

	public List<T> findAll() {
		return findAll(-1, -1);
	}
	
	public List<T> findAll(int startIndex, int endIndex) {
		Query query = em.createQuery(" from " + persistentClass.getSimpleName());
		return query.getResultList();
	}

	public T getReference(ID id) {
		logger.info("ID Passed: " + id);
		return em.getReference(persistentClass, id);
	}
	
	public T findByPrimaryKey(ID id) {
		logger.info("ID Passed: " + id);
		return em.find(persistentClass, id);
	}

	public void create(T entity) {
		logger.info("Entity passed : " + entity.toString());
		em.persist(entity);
		logger.info("Entity saved");
	}
	
	public T merge(T entity) {
		return em.merge(entity);
	}

	public EntityManager getEntityManager() {
		return em;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.em = entityManager;
	}

}
